<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('organization.orgName')">
          <el-input v-model="formSearch.orgName" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('organization.orgCode')">
          <el-input v-model="formSearch.orgCode" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('organization.category')">
          <el-input v-model="formSearch.category" clearable> </el-input>
          <!-- <el-select v-model="formSearch.category">
            <el-option
              :label="t('organization.categoryUnit')"
              value="UNIT"
            ></el-option>
            <el-option
              :label="t('organization.categoryDept')"
              value="DEPT"
            ></el-option>
          </el-select> -->
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('organization.status')">
          <el-select v-model="formSearch.status">
            <el-option
              :label="t('common.statusDisabled')"
              value="0"
            ></el-option>
            <el-option :label="t('common.statusEnabled')" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button :icon="Search" type="primary" @click="handleSearch">{{
            t("common.searchButton")
          }}</el-button>
          <el-button
            :icon="RefreshLeft"
            @click="formSearchRef.value.resetFields()"
            >{{ t("common.resetButton") }}</el-button
          >
          <search-input-expland
            @on-expland-change="(v:boolean)=>{ searchInputExpland=v}"
          ></search-input-expland>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-org-grid"
    row-key="orgId"
    defaultSort="ascending"
    defaultSortBy="levelCode"
    :request="handleLoadGrid"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <el-button type="primary" :icon="Plus" @click="handleAdd">{{
        t("organization.newOrganization")
      }}</el-button>
      <el-button :icon="Folder" @click="handlePreviewTree">{{
        t("organization.organizationTree")
      }}</el-button>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 account 仅在当前作用域有效 -->
    <template #orgName="slotProps">
      <el-link type="primary" @click="handleView(slotProps.row)">{{
        slotProps.row.orgName
      }}</el-link>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 status 仅在当前作用域有效 -->
    <template #status="slotProps">
      <el-switch
        v-model="slotProps.row.status"
        :active-value="1"
        :inactive-value="0"
        @change="handleStateChange($event, slotProps.row)"
      />
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
    <template #operate="slotProps">
      <el-link type="primary" @click="handleEdit(slotProps.row)">{{
        t("common.editButton")
      }}</el-link>
      &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row)"
        >{{ t("common.deleteButton") }}
      </el-link>
    </template>
  </data-grid>

  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
  <view-form ref="viewFormRef"></view-form>
  <tree-form ref="treeFormRef"></tree-form>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import SearchInputExpland from "../../../components/SearchInputExpland.vue";
import EditForm from "./edit.vue";
import ViewForm from "./view.vue";
import TreeForm from "./tree.vue";
import { Plus, Folder, Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../utils/utils";
import apiOrganization from "../api/organization";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
const treeFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);
// 查询区域表单数据
const formSearch = reactive({
  orgName: "",
  orgCode: "",
  category: "",
  status: "",
});

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      field: "orgId",
      type: "selection",
      align: "center",
      width: 55,
    },
    {
      title: () => t("organization.levelCode"),
      field: "levelCode",
      sortable: true,
      resizable: true,
      width: 200,
    },
    {
      title: () => t("organization.orgName"),
      field: "orgName",
      sortable: true,
      resizable: true,
      tdSlot: "orgName",
    },
    {
      title: () => t("organization.orgCode"),
      field: "orgCode",
      sortable: true,
      resizable: true,
      width: 200,
    },
    {
      title: () => t("organization.category"),
      field: "category",
      sortable: true,
      resizable: true,
      width: 150,
      // formatter: function (
      //   row: any,
      //   column: any,
      //   cellValue: string,
      //   index: number
      // ) {
      //   if (cellValue == "UNIT") {
      //     return t("organization.categoryUnit");
      //   } else if (cellValue == "DEPT") {
      //     return t("organization.categoryDept");
      //   }
      //   return "";
      // },
    },
    {
      title: () => t("organization.status"),
      field: "status",
      tdSlot: "status",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiOrganization
    .queryOrganizationListing(params)
    .then((response: any) => {
      data = response.data;
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
  // 返回数据给表格组件
  return data;
};

// 删除操作事件
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    t("organization.confirmDelete", { orgName: row.orgName }),
    {
      confirmButtonText: t("common.okButton"),
      cancelButtonText: t("common.cancelButton"),
    }
  )
    .then(() => {
      apiOrganization
        .deleteOrganization(row.orgId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            utils.infoNotification(
              t("organization.deleted", { orgName: row.orgName })
            );
          }
        })
        .catch((err: any) => {
          utils.errorNotification(t("common.submitException"), err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开组织机构树预览页面
const handlePreviewTree = () => {
  treeFormRef.value.show();
};
// 打开编辑页
const handleEdit = async (row: any) => {
  editFormRef.value.show(row);
};
// 新增、编辑页确定按钮回调事件
const onSubmitSuccess = (row: any) => {
  handleSearch();
};
// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};

const handleStateChange = (state: any, row: any) => {
  // console.log("handleStateChange", state, row);
  if (row.orgId != undefined) {
    // 避免第一次加载页面触发
    apiOrganization
      .changeOrganizationStatus(row.orgId, state == 1 ? 1 : 0)
      .then((response: any) => {
        if (response.data.code == 200) {
          handleSearch();
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
</script>
<style></style>
